#include "LOK2WindowManager.h"

LOK2WindowManager::LOK2WindowManager(SDL_Event *event) {
	m_Event = event;
	m_Lock = -1;
}

LOK2WindowManager::~LOK2WindowManager() { 
	m_Event = 0;
	m_Lock = -1;
}

void LOK2WindowManager::addWindow(SDLTextBox *pObject) {
	m_ObjList.push_back(pObject);
	pObject->setManager(this);
}

void LOK2WindowManager::manage() {
	int x = 0, y = 0, i = 0, j = -1;
	if(hasLock()) {
		m_ObjList[m_Lock]->inputHandler();
		return;
	}
	
	SDL_Rect box;
	for(i = 0; i < m_ObjList.size(); i++) {
		if(m_ObjList[i]->popupActive()) {
			m_ObjList[i]->setFocus(true);
			j = i;
		}
	}
	if(j != - 1) for(i = 0; i < m_ObjList.size(); i++) {
		if(i != j) m_ObjList[i]->setFocus(false);
	} else {
		switch(m_Event->type) {
		case SDL_MOUSEMOTION:
			x = m_Event->motion.x;
			y = m_Event->motion.y;
			for(i = 0; i < m_ObjList.size(); i++) {
				box = m_ObjList[i]->getRect();
		//		printf("x: %d, y: %d, box.x: %d, box.y: %d, box.w: %d, box.h: %d\n", x, y, box.x, box.y, box.w, box.h);
				if((x > box.x) && (x < box.x + box.w) && (y > box.y) && (y < box.y + box.h)) {
					m_ObjList[i]->setFocus(true);
				} else if(m_ObjList[i]->hasFocus()) m_ObjList[i]->setFocus(false);
			}
			break;
		case SDL_KEYDOWN:
			if(m_Event->key.keysym.mod & KMOD_CTRL) {
				if(m_Event->key.keysym.sym == SDLK_TAB) {
					for(i = 0; i < m_ObjList.size(); i++) {
						if(m_ObjList[i]->hasFocus()) {
							m_ObjList[i]->setFocus(false);
							if(i + 1 >= m_ObjList.size()) m_ObjList[0]->setFocus(true);
							else m_ObjList[i + 1]->setFocus(true);
						}
					}
				}
			} else {
				//set focus to the command line ..in a super hacky way ..implement an isInput() boolean function to decide
				//who gets focus
				m_ObjList[0]->setFocus(true);
				if(m_ObjList[1]->hasFocus()) m_ObjList[1]->setFocus(false);
			}
			break;
		}
	}
	for(i = 0; i < m_ObjList.size(); i++) m_ObjList[i]->inputHandler();
}

bool LOK2WindowManager::requestLock(SDLTextBox *caller) {
	if(m_Lock != -1) return false;
	for(int i = 0; i < m_ObjList.size(); i++) {
		if(caller == m_ObjList[i]) m_Lock = i;
	}
	if(m_Lock != -1) return true;
	return false;
}

bool LOK2WindowManager::releaseLock(SDLTextBox *caller) {
	if(m_Lock == -1) return false;
	if(caller == m_ObjList[m_Lock]) m_Lock = -1;
	if(m_Lock == -1) return true;
	return false;
}

bool LOK2WindowManager::hasLock() {
	if(m_Lock == -1) return false;
	return true;
}

		